<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CompanyVO } from '#/api/company/manage/model';

import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { useUserStore } from '@vben/stores';
import { getVxePopupContainer } from '@vben/utils';

import {
  Dropdown,
  Menu,
  MenuItem,
  Popconfirm,
  Space,
  Tooltip,
} from 'ant-design-vue';

import {
  useVbenVxeGrid,
  vxeCheckboxChecked,
  vxeCheckboxCheckedCount,
} from '#/adapter/vxe-table';
import {
  personalFavoriteAddMemberByCompanyId,
  personalFavoriteAddMemberByCompanySearch,
} from '#/api/company/favorite/personal';
import {
  companyBatchSetTags,
  companyDownloadImportTemplate,
  companyImport,
  companyPage,
  companyUnlock,
} from '#/api/company/manage';
import { useAdvancedFilter } from '#/components/advanced-filter';
import addCompanyToFavoriteModal from '#/components/favorite/src/add-company-modal.vue';
import addEmployeeToFavoriteModal from '#/components/favorite/src/add-employee-modal.vue';
import importModal from '#/components/import/src/import-modal.vue';
import tagSelectModal from '#/components/tag/src/tag-select-modal.vue';

import companyDrawer from './company-drawer.vue';
import { columns, querySchema } from './data';
import mergeModal from './merge-modal.vue';
import transferModal from './transfer-modal.vue';

interface Props {
  pageType?: string;
}

const props = withDefaults(defineProps<Props>(), {
  pageType: 'all',
});

const { hasAccessByCodes } = useAccess();
const userStore = useUserStore();
const userId = computed(() => {
  return userStore.userInfo?.userId;
});

const searchData = ref<Record<string, any>>();
const total = ref(0);
const route = useRoute();
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  handleReset: async () => {
    filterApi.clearAllExposed();
    const { formApi, reload } = tableApi;
    await formApi?.resetForm();
    const formValues = formApi.form.values;
    formApi.setLatestSubmissionValues(formValues);
    await reload(formValues);
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // fieldMappingTime: [
  //   ['tagInfo', ['tagIds', 'tagOp'], null],
  //   ['addressMap', ['provinceId', 'cityId', 'areaId'], null],
  // ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: false,
    // 翻页时保留选中状态
    reserve: false,
    // 点击行选中
    // trigger: 'row',
  },
  // 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
  // columns: columns(),
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        console.log(formValues);
        const _filter = route.query._filter_;
        const values = filterApi.getFormValues();
        console.log('filterApi Values：', values);
        filterApi.filterParams(formValues, values);
        console.log('父组件调用API获取过滤后的高级筛选参数：', formValues);
        let queryData = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        };
        if (props.pageType === 'my') {
          queryData.followUpId = userId.value;
        }
        if (props.pageType === 'other' && _filter) {
          try {
            const queryParam = JSON.parse(
              decodeURIComponent(escape(atob(_filter as string))),
            );
            queryData = { ...queryData, ...queryParam };
            for (const key in queryParam) {
              tableApi?.formApi?.updateSchema([
                { fieldName: key, componentProps: { disabled: true } },
              ]);
            }
          } catch (error) {
            console.log(error);
          }
        }

        searchData.value = queryData;
        const resp = await companyPage(queryData);
        total.value = resp.total;

        return resp;
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'company-manage-index',
  showOverflow: false,
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    // 需要控制不同的事件 radio也会触发checkbox事件
    checkboxChange: checkBoxEvent,
    checkboxAll: checkBoxEvent,
  },
});

const [AdvancedFilter, filterApi] = useAdvancedFilter({
  tableApi,
});

const [CompanyDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: companyDrawer,
});

function checkBoxEvent() {
  // const records = tableApi.grid.getCheckboxRecords();
}

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

async function handleEdit(row: CompanyVO) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

const router = useRouter();

function handleDetails(row: CompanyVO) {
  router.push(`/company/manage/details/${row.id}`);
}

// 去呼叫
function handleCall(row: CompanyVO) {
  router.push({
    path: `/contact/task/listWorkbench`,
    query: { type: 'company', companyId: row.id },
  });
}

// 解锁
async function handleUnlock(row: CompanyVO) {
  await companyUnlock(row.id);
  await tableApi.reload();
}

// 合并
const [MergeModal, mergeModalApi] = useVbenModal({
  connectedComponent: mergeModal,
  destroyOnClose: true,
});

function handleMerge() {
  const records = tableApi.grid.getCheckboxRecords();
  mergeModalApi.setData({ records });
  mergeModalApi.open();
}

// 转移跟进人
const [TransferModal, transferModalApi] = useVbenModal({
  connectedComponent: transferModal,
  destroyOnClose: true,
});

function handleTransfer() {
  const records = tableApi.grid.getCheckboxRecords();
  const ids = records.map((v) => v.id);
  transferModalApi.setData({ ids });
  transferModalApi.open();
}

// 批量加入收藏夹
// 企业收藏夹弹窗
const [AddCompanyToFavoriteModal, addCompanyToFavoriteModalApi] = useVbenModal({
  connectedComponent: addCompanyToFavoriteModal,
  destroyOnClose: true,
});

// 人员收藏夹弹窗
const [AddEmployeeToFavoriteModal, addEmployeeToFavoriteModalApi] =
  useVbenModal({
    connectedComponent: addEmployeeToFavoriteModal,
    destroyOnClose: true,
  });

function handleFavoriteMenuClick(e: any) {
  const type = e.key;
  if (type === 'checkCompany') {
    // 勾选加入企业收藏夹
    const records = tableApi.grid.getCheckboxRecords();
    addCompanyToFavoriteModalApi.setData({
      type: 'check',
      records,
      total: records.length,
    });
    addCompanyToFavoriteModalApi.open();
  }
  if (type === 'searchCompany') {
    // 筛选加入企业收藏夹
    addCompanyToFavoriteModalApi.setData({
      type: 'search',
      searchData: searchData.value,
      total: total.value,
    });
    addCompanyToFavoriteModalApi.open();
  }
  if (type === 'checkEmployee') {
    // 勾选加入人员收藏夹
    const records = tableApi.grid.getCheckboxRecords();
    addEmployeeToFavoriteModalApi.setData({
      type: 'check',
      records,
      total: records.length,
    });
    addEmployeeToFavoriteModalApi.open();
  }
  if (type === 'searchEmployee') {
    // 筛选加入人员收藏夹
    addEmployeeToFavoriteModalApi.setData({
      type: 'search',
      searchData: searchData.value,
      total: total.value,
    });
    addEmployeeToFavoriteModalApi.open();
  }
}

// 批量打标签弹窗
const [TagSelectModal, tagSelectModalApi] = useVbenModal({
  connectedComponent: tagSelectModal,
  destroyOnClose: true,
});

function handleBatchTagOpen() {
  tagSelectModalApi.open();
}

async function handleBatchTagConfirm(data: any) {
  console.log('批量打标签选择确认：', data.ids);
  tagSelectModalApi.lock(true);
  const records = tableApi.grid.getCheckboxRecords();
  const companyIds = records.map((v) => v.id);
  await companyBatchSetTags({ labelIds: data.ids, ids: companyIds });
  tagSelectModalApi.lock(false);
  tagSelectModalApi.close();
  await tableApi.reload();
}

// 导入
const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: importModal,
  destroyOnClose: true,
});

function handleImport() {
  importModalApi.open();
}

async function handleImportSuccess() {
  await tableApi.query();
}

onMounted(() => {
  // console.log('route参数:', route.query);
});
</script>

<template>
  <Page :auto-content-height="true">
    <AdvancedFilter />
    <BasicTable>
      <!--<template #form-expand-after>123</template>-->
      <template #table-title>
        <main-title text="企业列表" />
      </template>
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['company:manager:import']"
            @click="handleImport"
          >
            导入
          </a-button>
          <Tooltip
            title="合并多个勾选的企业，仅合并员工与标签，数据将保留在目标企业中"
          >
            <a-button
              v-access:code="['company:manager:merge']"
              :disabled="vxeCheckboxCheckedCount(tableApi) < 2"
              @click="handleMerge"
            >
              合并({{ vxeCheckboxCheckedCount(tableApi) }})
            </a-button>
          </Tooltip>
          <Tooltip title="将勾选的企业转移给其他跟进人，仅变更跟进人归属">
            <a-button
              v-access:code="['company:manager:transferFollowUp']"
              :disabled="!vxeCheckboxChecked(tableApi)"
              @click="handleTransfer"
            >
              转移跟进人({{ vxeCheckboxCheckedCount(tableApi) }})
            </a-button>
          </Tooltip>
          <Dropdown>
            <template #overlay>
              <Menu @click="handleFavoriteMenuClick">
                <span v-access:code="['company:favorite:addMember']">
                  <MenuItem
                    key="checkCompany"
                    :disabled="!vxeCheckboxChecked(tableApi)"
                  >
                    按勾选加入企业收藏夹({{
                      vxeCheckboxCheckedCount(tableApi)
                    }})
                  </MenuItem>
                </span>
                <span v-access:code="['company:favorite:addMemberBySearch']">
                  <MenuItem key="searchCompany" :disabled="total === 0">
                    按筛选条件结果加入企业收藏夹({{ total }})
                  </MenuItem>
                </span>
                <span v-access:code="['employee:favorite:addByCompanyId']">
                  <MenuItem
                    key="checkEmployee"
                    :disabled="!vxeCheckboxChecked(tableApi)"
                  >
                    按勾选加入人员收藏夹({{
                      vxeCheckboxCheckedCount(tableApi)
                    }})
                  </MenuItem>
                </span>
                <span v-access:code="['employee:favorite:addByCompanySearch']">
                  <MenuItem key="searchEmployee" :disabled="total === 0">
                    按筛选条件结果加入人员收藏夹({{ total }})
                  </MenuItem>
                </span>
              </Menu>
            </template>
            <a-button
              v-access:code="[
                'company:favorite:addMember',
                'company:favorite:addMemberBySearch',
                'employee:favorite:addByCompanyId',
                'employee:favorite:addByCompanySearch',
              ]"
            >
              批量加入收藏夹
            </a-button>
          </Dropdown>
          <Tooltip
            title="批量为勾选的企业添加企业标签，仅新增不会覆盖或删除原有标签"
          >
            <a-button
              v-access:code="['company:manager:addLabel']"
              :disabled="!vxeCheckboxChecked(tableApi)"
              @click="handleBatchTagOpen"
            >
              批量打标签({{ vxeCheckboxCheckedCount(tableApi) }})
            </a-button>
          </Tooltip>
          <a-button
            type="primary"
            v-access:code="['company:manager:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['company:manager:query']"
            @click="handleDetails(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <ghost-button
            v-access:code="['company:manager:edit']"
            @click.stop="handleEdit(row)"
          >
            {{
              row.certificationStatus === 1 ? $t('pages.common.edit') : '认证'
            }}
          </ghost-button>
          <ghost-button
            v-if="
              hasAccessByCodes(['company:manager:trrtCall']) &&
              row.employeeCount > 0
            "
            class="btn-success"
            @click.stop="handleCall(row)"
          >
            呼叫
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确定解锁？"
            @confirm="handleUnlock(row)"
          >
            <ghost-button
              v-show="
                hasAccessByCodes(['company:manager:unlock']) &&
                !row.tycCompanyId &&
                row.certificationStatus === 1
              "
              class="btn-success"
              @click.stop=""
            >
              解锁
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <CompanyDrawer @reload="tableApi.reload()" />
    <ImportModal
      file-dict-name="企业管理"
      :import-api="companyImport"
      :download-api="companyDownloadImportTemplate"
      @reload="handleImportSuccess"
    />
    <TransferModal @reload="tableApi.reload()" />
    <MergeModal @reload="tableApi.reload()" />
    <TagSelectModal
      :tag-type="1"
      :show-op="false"
      :confirmed-close="false"
      @confirm="handleBatchTagConfirm"
    >
      <template #prepend-footer>
        <div class="mr-[10px]">
          已选
          <span class="text-red-500">
            {{ vxeCheckboxCheckedCount(tableApi) }}
          </span>
          家企业
        </div>
      </template>
    </TagSelectModal>
    <AddCompanyToFavoriteModal @reload="tableApi.reload()" />
    <AddEmployeeToFavoriteModal
      btn-text="确认加入"
      :add-by-check-company-api="personalFavoriteAddMemberByCompanyId"
      :add-by-search-api="personalFavoriteAddMemberByCompanySearch"
      @reload="tableApi.reload()"
    />
  </Page>
</template>
